import type { CascaderTypeEntityReq } from "@/api/types";
import type { UseBaseForm } from "@/composables";
import { ElMessage } from "element-plus";
import { cascaderTypeApi } from "@/api";
import { useBaseForm } from "@/composables";
import { $t } from "@/plugins/i18n";
import { apiCall } from "@/utils/http/apiCall";
import { onlySubmitData } from "@/utils/tools";

interface UseCascaderTypeForm extends UseBaseForm<CascaderTypeEntityReq> {
    getInitFormData: () => CascaderTypeEntityReq;
    handleSubmit: (isEdit: boolean, callback?: () => void) => Promise<void>;
}

export function useCascaderTypeForm(): UseCascaderTypeForm {
    /** 获取初始表单数据 */
    const getInitFormData = (): CascaderTypeEntityReq => ({
        id: undefined,
        name: "",
        code: "",
        remark: null,
    });

    const { formRef, formData, submitLoading, resetForm } = useBaseForm(getInitFormData);

    /** 提交表单 */
    async function handleSubmit(isEdit: boolean, callback?: () => void): Promise<void> {
        if (!(await formRef.value?.validate())) return;

        submitLoading.value = true;
        const payload = onlySubmitData(getInitFormData(), formData);

        apiCall(
            () => isEdit
                ? cascaderTypeApi.update(payload)
                : cascaderTypeApi.create(payload),
            (data, resp) => {
                ElMessage.success($t(resp.message));
                callback?.();
            },
            {
                onFinally: () => {
                    submitLoading.value = false;
                },
            },
        );
    }

    return {
        getInitFormData,
        formData,
        resetForm,
        formRef,
        submitLoading,
        handleSubmit,
    };
}
